package cn.jksoft.businessclient.widgets;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


import java.util.Map;

import cn.jksoft.businessclient.utils.CommonUtils;
import cn.jksoft.businessclient.utils.DialogHelp;

public class CustomWebView extends WebView {
    protected static final String TAG = CustomWebView.class.getSimpleName();
    private Context context;
    private MySwipeRefreshLayout swipeLayout;
    private Dialog mDialog;

    public CustomWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        initView();
    }

    public CustomWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initView();
    }

    public CustomWebView(Context context) {
        super(context);
        this.context = context;
        initView();
    }

    private void initView() {
        initSetting();
    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            initSwipeLayout(url);
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            try {
                if (swipeLayout == null) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    mDialog = DialogHelp.getWaitDialog(getContext(), "请稍后...");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            try {
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            super.onPageFinished(view, url);
        }
    }

    public void initSwipeLayout(String url) {
        // if (url.equals(Constant.SERVER_INDEX)) {
//		swipeLayout.setCanRefresh(false);
        // } else {
        if (swipeLayout != null) {
            swipeLayout.setCanRefresh(true);
        }
        // }
    }

    private void initSetting() {
        WebSettings settings = this.getSettings();
        String ua = settings.getUserAgentString();
       // LogUtils.v("ua=" + ua);
        settings.setUserAgentString(ua + "; AndroidWeb/"
                + CommonUtils.getVersionName(context) + "_"
                + CommonUtils.getVersionCode(context));
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setDomStorageEnabled(true);
        settings.setJavaScriptEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setPluginState(WebSettings.PluginState.ON);
//        settings.setUseWideViewPort(true);
        settings.setAppCachePath(context.getCacheDir() + "/AppCache");
        settings.setAllowFileAccess(true);
        // this.addJavascriptInterface(new UserInterface(context, this),
        // "xw_user");
        // this.addJavascriptInterface(new FunctionInterface(context),
        // "xw_func");
        this.setWebViewClient(new MyWebViewClient());
        this.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
             //   LogUtils.v(newProgress + "");
                if (swipeLayout != null) {
                    if (newProgress == 100) {
                        // 隐藏进度条
                        swipeLayout.setRefreshing(false);
                    } else {
                        if (!swipeLayout.isRefreshing())
                            swipeLayout.setRefreshing(true);
                    }
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onGeolocationPermissionsHidePrompt() {
                super.onGeolocationPermissionsHidePrompt();
                Log.i(TAG, "onGeolocationPermissionsHidePrompt");
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin,
                                                           final GeolocationPermissions.Callback callback) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setMessage("是否允许获取您的位置？");
                DialogInterface.OnClickListener dialogButtonOnClickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,
                                        int clickedButton) {
                        if (DialogInterface.BUTTON_POSITIVE == clickedButton) {
                            callback.invoke(origin, true, true);
                        } else if (DialogInterface.BUTTON_NEGATIVE == clickedButton) {
                            callback.invoke(origin, false, false);
                        }
                    }

                };
                builder.setPositiveButton("允许", dialogButtonOnClickListener);
                builder.setNegativeButton("拒绝", dialogButtonOnClickListener);
                builder.show();
                super.onGeolocationPermissionsShowPrompt(origin, callback);
                Log.i(TAG, "onGeolocationPermissionsShowPrompt");
            }

        });
    }

    @Override
    public void loadUrl(String url) {
        initSwipeLayout(url);
        super.loadUrl(url);
    }

    @Override
    public void loadUrl(String url, Map<String, String> additionalHttpHeaders) {
        initSwipeLayout(url);
        super.loadUrl(url, additionalHttpHeaders);
    }

    public MySwipeRefreshLayout getSwipeLayout() {
        return swipeLayout;
    }

    public void setSwipeLayout(MySwipeRefreshLayout swipeLayout) {
        this.swipeLayout = swipeLayout;
    }
}
